define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'jstree'], function ($, undefined, Backend, Table, Form) {

    //读取选中的条目
    $.jstree.core.prototype.get_all_checked = function (full) {
        var obj = this.get_selected(), i, j;
        for (i = 0, j = obj.length; i < j; i++) {
            obj = obj.concat(this.get_node(obj[i]).parents);
        }
        obj = $.grep(obj, function (v, i, a) {
            return v != '#';
        });
        obj = obj.filter(function (itm, i, a) {
            return i == a.indexOf(itm);
        });
        return full ? $.map(obj, $.proxy(function (i) {
            return this.get_node(i);
        }, this)) : obj;
    };

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'prl/articles/index',
                    add_url: 'prl/articles/add',
                    edit_url: '',
                    del_url: 'prl/articles/del',
                    multi_url: 'prl/articles/multi',
                    table: 'prl_articles',
                }
            });
            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'weigh',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'title', title: __('Title')},
                        {field: 'image', title: __('Image'), events: Table.api.events.image, formatter: Table.api.formatter.image},
                        {field: 'admin_name', title: __('Admin_id'), formatter: Table.api.formatter.search},
                        {field: 'releasetime', title: __('Releasetime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'weigh', title: __('Weigh')},
                        {field: 'status', title: __('Status'), searchList: {"0":__('Status 0'),"1":__('Status 1')}, formatter: Table.api.formatter.status},
                        {field: 'operate'
                            , title: __('Operate')
                            , table: table
                            , events: Table.api.events.operate
                            , formatter: Table.api.formatter.operate
                            , buttons: [{
                                name: __('Edit')
                                , title: __('Edit')
                                , icon: 'fa fa-pencil'
                                , classname: 'btn btn-success btn-edit btn-disabled btn-xs btn-addtabs'
                                , url: 'prl/articles/edit'
                            }]
                        }
                    ]
                ],
                queryParams : function (params) {
                    var filter = JSON.parse(params.filter);
                    var op = JSON.parse(params.op);
                    if(Config.ids != null){
                        filter.channels_id = Config.ids;
                        op.channels_id = "=";
                    }
                    params.filter = JSON.stringify(filter);
                    params.op = JSON.stringify(op);
                    return params;
                },
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
            //渲染树
            Controller.api.rendertree(Config.treeList);

            //全选和展开
            $(document).on("click", "#checkall", function () {
                $("#channelsList").jstree($(this).prop("checked") ? "check_all" : "uncheck_all");
            });

            $(document).on("click", "#expandall", function () {
                $("#channelsList").jstree($(this).prop("checked") ? "open_all" : "close_all");
            });

            //选中栏目
            $("#channelsList").on("changed.jstree", function (e, data) {
                var options = table.bootstrapTable('getOptions');
                options.pageNumber = 1;
                options.queryParams = function (params) {
                    params.filter = JSON.stringify(data.selected.length > 0 ? {channels_id: data.selected.join(",")} : {});
                    params.op = JSON.stringify(data.selected.length > 0 ? {channels_id: 'in'} : {});
                    return params;
                }
                table.bootstrapTable('refresh', {});
                return false;
            })
        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'prl/articles/recyclebin',
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'title', title: __('Title'), align: 'left'},
                        {
                            field: 'deletetime',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            width: '130px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'Restore',
                                    text: __('Restore'),
                                    classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                    icon: 'fa fa-rotate-left',
                                    url: 'prl/articles/restore',
                                    refresh: true
                                },
                                {
                                    name: 'Destroy',
                                    text: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    url: 'prl/articles/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
            $(document).on("change", "form input[name='row[title]']", function (e) {
                $("#c-seo_title").val($(this).val() + '-' + Config.site.name);
                $("#c-seo_keywords").val($(this).val() + '-' + Config.site.name);
            })

            $(document).on("change", "form textarea[name='row[summary]']", function (e) {
                $("#c-seo_description").val($(this).val() + '-' + Config.site.name);
            })
        },
        edit: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"),function(){
                    //延时关闭当前添加选项卡
                    setInterval(function(){
                        top.window.$("ul.nav-addtabs li[class='active']").find(".fa-remove").trigger("click")
                    },1000)
                });

                $(document).on("hide.bs.select", "form select[name='row[channels_id]']", function (e) {
                    var load = Layer.load();
                    var channel_ids = $(this).selectpicker('val')
                    var row_id = $("#row-id").val();
                    if(channel_ids == null){
                        Layer.close(load);
                        return false;
                    }
                    $.ajax({
                        url:'prl/models/getModelField'
                        , type:'POST'
                        , data:{channel_ids : channel_ids, row_id:row_id}
                        , success:function(e) {
                            Layer.close(load);
                            $("#table").html(e.data);
                            Form.api.bindevent($("#table"));
                        }
                        , error : function() {
                            Layer.close(load);
                            Toastr.error("服务器发生错误!");
                        }
                    })
                });

                $(document).on("loaded.bs.select", "form select[name='row[channels_id]']", function (e) {
                    $("form select[name='row[channels_id]']").trigger("hide.bs.select");
                });
            },
            rendertree: function (content) {
                $("#channelsList").jstree({
                            "themes": {"stripes": true},
                            "checkbox": {
                                "keep_selected_style" : false,
                                "cascade_to_disabled" : false,
                                "three_state" : false
                            },
                            "types": {
                                "0": {
                                    "icon": "fa fa-home",
                                },
                                "1": {
                                    "icon": "fa fa-columns",
                                },
                                "2": {
                                    "icon": "fa fa-list",
                                },
                                "4": {
                                    "icon": "fa fa-file-o",
                                },
                                "5": {
                                    "icon": "fa fa-envelope-o",
                                },
                                "6": {
                                    "icon": "fa fa-link",
                                }
                            },
                            "plugins": ["checkbox", "types"],
                            "state": {"opened" : true},
                            "core": {
                                'check_callback': true,
                                'multiple' : false,
                                "data": content
                            }
                        });
            }
        }
    };
    return Controller;
});